package main

import (
	"encoding/json"
	"math/rand"

	"gofw-im/lib/define"
	"gofw-im/lib/proto"
)

type pushArg struct {
	ServerId int8
	UserId   string
	Msg      []byte
	RoomId   int32
}

var pushChs []chan *pushArg

func InitPush() {
	pushChs = make([]chan *pushArg, conf.Base.PushChan)
	for i := 0; i < len(pushChs); i++ {
		pushChs[i] = make(chan *pushArg, conf.Base.PushChanSize)
		go processPush(pushChs[i])
	}
}

func processPush(ch chan *pushArg) {
	var arg *pushArg
	for {
		arg = <-ch
		PushSingleToComet(arg.ServerId, arg.UserId, arg.Msg)
	}
}

func push(msg string) (err error) {
	m := &proto.RedisMsg{}
	msgStr := []byte(msg)
	if err = json.Unmarshal(msgStr, m); err != nil {
		return
	}
	switch m.Op {
	case define.OP_SINGLE_SEND:
		pushChs[rand.Int()%conf.Base.PushChan] <- &pushArg{ServerId: m.ServerId, UserId: m.UserId, Msg: m.Msg, RoomId: m.RoomId}
		break
	case define.OP_ROOM_SEND:
		broadcastRoomToComet(m.RoomId, m.Msg)
		break
	case define.OP_ROOM_COUNT_SEND:
		broadcastRoomCountToComet(m.RoomId, m.Count)
	case define.OP_ROOM_INFO_SEND:
		broadcastRoomInfoToComet(m.RoomId, m.RoomUserInfo)
	}

	return
}
